import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/bean/calendar_attendance_status_bean.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/widgets/attend_picture_correction_widget.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/widgets/attend_record_remark_dialog.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import '../attend_record_calendar_page.dart';
import '../attendance_record_today_viewmodel.dart';

class ModifyPersonalClockRecordWidget extends StatefulWidget {
  final int dayTime;
  final String fuid;
  final DateTime selectDayTime;

  final VoidCallback onChanged;

  const ModifyPersonalClockRecordWidget({
    Key key,
    this.dayTime,
    this.fuid,
    this.selectDayTime,
    this.onChanged,
    // this.putpicurl,
  }) : super(key: key);

  @override
  _ModifyPersonalClockRecordWidgetState createState() =>
      _ModifyPersonalClockRecordWidgetState();

  //跳转方法  <dynamic>压出界面的返回值
  static Future<dynamic> navigatorPush(
      BuildContext context,
      int dayTime,
      String fuid,
      DateTime selectDayTime,
      VoidCallback onChanged,
      // String putpicurl
      ) {

    return RouterUtils.routeForFutureResult(
        context,
        ModifyPersonalClockRecordWidget(
          dayTime: dayTime,
          fuid: fuid,
          selectDayTime: selectDayTime,
          onChanged: onChanged,
            // putpicurl:putpicurl
        ));
  }
}

class _ModifyPersonalClockRecordWidgetState
    extends BaseState<ModifyPersonalClockRecordWidget> {
  AttendanceRecordTodayViewModel viewModel;
  int month;
  int year;
  int day;

  String Cpid;

  String punchstatus; // 上班状态 00出勤01缺勤 02纠正 03加班 04非加班 05请假 06外出 07确定加班 99异常'
  String punchstatusCorrect; //原状态 99 异常   01 缺勤  null 正常或者加班
  String type; //00纠正 01还原
  String correctionBarText;
  StreamSubscription eventStreamSubscription;
  int dayTime;
  CalendarAttendanceStatusBean listBean; //所有数据bean
  List<DayUserPunchListBean> dayUserPunchList; //每条考勤数据
  OperatorInfoBean operatorInfoBean; //登录人纠正状态
  PunchuserBean punchuser;
  FaceuserBean faceuserBean;
  // rest  00  休息日  01工作日
  // normal  00 正常  01异常
  // absence  00 缺勤  01出勤
  // overtime  00 加班 01不加班

  bool showBackup;

  DayUserPunchListBean itemBeanshowBackup;

  @override
  void initState() {
    super.initState();
    showBackup = true;
    dayUserPunchList = new List<DayUserPunchListBean>();
    month = widget?.selectDayTime.month;
    year = widget?.selectDayTime.year;
    day = widget?.selectDayTime.day;
    dayTime = widget?.dayTime;
    viewModel = AttendanceRecordTodayViewModel(this,() => dayTime);
    viewModel.valueNotifier.addListener(() {
      listBean = viewModel?.valueNotifier?.value;
      punchuser = listBean?.data?.punchuser;
      faceuserBean = listBean?.data?.faceuser;
      dayUserPunchList = listBean?.data?.dayUserPunchList;
      operatorInfoBean = listBean?.data?.operatorInfo;
      punchstatusCorrect = operatorInfoBean?.punchstatus ?? "00";
      punchstatus = punchuser?.punchstatus;
      type = operatorInfoBean?.type ?? "00";
      Cpid = listBean?.data?.cpid;
      setState(() {});
      showBackup = false;
    });
    eventStreamSubscription =
        VgEventBus.global.on<ModifyAttendanceRefreshEvent>().listen((event) {
          refreshData();
        });


    // onTapChangeText = onTapChangeText;
    refreshData();
  }

  void refreshData() {
    viewModel.choiceDayAttendanceData(dayTime ?? 0, widget?.fuid);
  }


  void setModifyAttendanceData(BaseCallback callback) {
    viewModel.modifyAttendanceData(Cpid, punchstatusCorrect, type, callback);
  }

  void setUserPunchRecordRecalculate(BaseCallback callback) {
    viewModel.userPunchRecordRecalculate(Cpid, callback);
  }

  @override
  void dispose() {
    super.dispose();
    eventStreamSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      // backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toAttendanceWidget(),
    );
  }

  Widget _toAttendanceWidget() {
    return ValueListenableBuilder(
      valueListenable: viewModel?.valueNotifier,
      builder: (BuildContext context, CalendarAttendanceStatusBean calendarAttendanceStatusBean, Widget child){
        return VgPlaceHolderStatusWidget(
          loadingStatus: (calendarAttendanceStatusBean?.data?.dayUserPunchList?.length??0) == 0 && calendarAttendanceStatusBean?.data?.punchuser?.punchstatus==null && calendarAttendanceStatusBean?.data?.faceuser==null,
          // errorStatus : dayUserPunchList?.length == 0&& punchstatusCorrect!=null,
          // emptyStatus : dayUserPunchList?.length == 0&& punchstatusCorrect!=null,
          child:child
        );
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          _toTopBarWidget(),//表头
            if(_showDefaultWidget())
           punchuser?.backup!=""&&punchuser?.backuptime!=null ? _reamrkText() : _defaultEmptyCustomWidget(),
            //数据校正栏(列表有数据，并且有状态，状态非00)punchstatus!="00"&&
          if(!_showDefaultWidget())
            if(punchstatus != null && punchstatus!="00")
              _changeableDataCorrectionBar(),
          if(listBean !=null)//列表数据
            _attendanceDataList(),
          // Spacer(),
          _toHorizontalBar()
          // Spacer(),
        ],
      ),
    );
  }

  bool _showDefaultWidget(){
    //无数据展示
    if(dayUserPunchList?.length == 0){
      if(punchstatus == null){
        if(punchstatus == "01" || punchstatus == "02" || punchstatus == "05"){
          return false;
        }
        return true;
      }
      if(punchstatus == "05" && !(punchuser?.isRule()??false)){
        return true;
      }
    }
    return false;
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      // navFunction:(){
      //   RouterUtils.pop(context);
      // },
      // isShowSecondRightWdiget:true,
      isShowBackRightWdiget:true,
      backRightWidget: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: (){
          PersonDetailPage.navigatorPush(context,faceuserBean?.fuid,pages: "CheckInStatisticsPage");
        },
        child: Container(
          child: Center(
            child: Row(
              children: <Widget>[
                ClipOval(
                  child: Container(
                    height: 28,
                    width: 28,
                    child: VgCacheNetWorkImage(
                        showOriginEmptyStr(faceuserBean?.putpicurl) ??showOriginEmptyStr(faceuserBean?.napicurl)?? "",
                      fit: BoxFit.cover,
                      defaultErrorType: ImageErrorType.head,
                      defaultPlaceType: ImagePlaceType.head,
                      imageQualityType: ImageQualityType.middleDown,
                    ),
                  ),
                ),
                SizedBox(
                  width: 8,
                ),
                Text(
                  "${VgStringUtils.subStringAndAppendSymbol(faceuserBean?.name ?? "用户名", 8,symbol: "...")}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.white, fontSize: 15, fontWeight: FontWeight.w600),
                ),
              ],
            ),
          ),
        ),
      ),

      rightWidget: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          _preDayWidget(),
          //标题
          Container(
            // padding: EdgeInsets.symmetric(horizontal: 6),
            child: Center(
              child: Text(
                "$year年$month月$day日",
                style: TextStyle(
                    color: Color(0xFFFFFFFF), fontSize: 15, height: 1.2),
              ),
            ),
          ),
          _nextDayWidget()
        ],
      ),

    );
  }

  Widget _addRemarksBar(){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        if(Cpid == ""){
          VgToastUtils.toast(context, "暂无打卡数据");
          return;
        }
        AttendRecordRemarkDialog.navigatorPushDialog(context,Cpid);
      },
      child: Container(
        padding: const EdgeInsets.only(left: 15),
        // color: ThemeRepository.getInstance().getLineColor_3A3F50(),
        height: 52,
        child: Row(
          children: [
            Image.asset("images/add_ico.png",color: Colors.blue,width: 17,),
            SizedBox(width: 6,),
            Text("本日备注",style: TextStyle(color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),fontSize: 15),),
          ],

        ),
      ),
    );
  }

  Widget _reamrkText(){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        if(Cpid == ""){
          VgToastUtils.toast(context, "暂无打卡数据");
          return;
        }
        AttendRecordRemarkDialog.navigatorPushDialog(context,Cpid,backup: punchuser?.backup);
      },
      child: Container(
        padding: const EdgeInsets.only(left: 15),
        // color: ThemeRepository.getInstance().getLineColor_3A3F50(),
        height: 52,
        child: Row(
          children: [
            Text(
              "${punchuser?.backupname ?? "操作人"}/${getMonthAndDayStr(punchuser?.backuptime)}  ",
              style: TextStyle(
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  fontSize: 15),
            ),
            Container(
              width: 225,
              child: Text(
                "${punchuser?.backup ?? ""}",
                style: TextStyle(
                    color:
                        ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    fontSize: 15),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Spacer(),
            Container(
              child: Image.asset(
                "images/index_arrow_ico.png",
                width: 6,
                color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
              ),
            ),
            SizedBox(width: 15,)
          ],
        ),
      ),
    );
  }

  ///两位数
  static String twoDigits(int n) {
    if (n == null || n < 0) {
      return "00";
    }
    if (n >= 10) return "$n";
    return "0$n";
  }

  ///获取月和日字符串
  static String getMonthAndDayStr(int timeStramp) {
    if (timeStramp == null || timeStramp <= 0) {
      return null;
    }
    //转成毫秒
    int tmpTimeStramp = timeStramp * 1000;
    DateTime dateTime = DateUtil.getDateTimeByMs(tmpTimeStramp);
    if (dateTime == null) {
      return null;
    }
    return twoDigits(dateTime.month).toString() +
        "-" +
        twoDigits(dateTime.day).toString() +
        ":";
  }

  int getCurrentMonthTimeStramp(DateTime _dateTime) {
    // DateTime _dateTime = DateTime?.parse(dateDayTime);
    if (_dateTime == null) {
      return null;
    }
    return (DateTime(_dateTime.year, _dateTime.month, _dateTime.day)
                .millisecondsSinceEpoch /
            1000)
        .floor();
  }

  ///点击减少一天
  _preDayWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        DateTime nextMonth = DateTime(year, month, day - 1);
        year = nextMonth.year;
        month = nextMonth.month;
        day = nextMonth.day;
        dayTime = getCurrentMonthTimeStramp(nextMonth);
        refreshData();
        // if(dayUserPunchList == null && dayUserPunchList?.length == 0)onTapNextDay = false;
        setState(() {});
      },
      child: Container(
        padding: EdgeInsets.only(top: 13, bottom: 13, left: 15, right: 11),
        alignment: Alignment(0.5,0),
        child: Image.asset(
          "images/calendar_previous_ico.png",
          height: 16,
        ),
      ),
    );
  }

  ///点击添加一天
  _nextDayWidget() {
    bool isSameMonth = (DateTime.now().year == year &&
        DateTime.now().month == month &&
        DateTime.now().day == day);
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        DateTime nextMonth = DateTime(year, month, day + 1);
        if (nextMonth.isAfter(DateTime.now())) {
          return;
        }
        year = nextMonth.year;
        month = nextMonth.month;
        day = nextMonth.day;
        dayTime = getCurrentMonthTimeStramp(nextMonth);
        refreshData();
        // if(dayUserPunchList == null && dayUserPunchList?.length == 0)onTapNextDay = false;
        setState(() {});
      },
      child: Opacity(
          opacity: isSameMonth ? 0.3 : 1,
          child: Container(
            padding: EdgeInsets.only(top: 13, bottom: 13, left: 11, right: 5),
            alignment: Alignment(0.5,0),
            child: Image.asset(
              "images/calendar_next_ico.png",
              height: 16,
            ),
          )),
    );
  }

  Widget _attendanceDataList() {
    return Expanded(
        child: Container(
            child: ListView.separated(
          itemCount: dayUserPunchList?.length ?? 0,
          physics: BouncingScrollPhysics(),
          padding: const EdgeInsets.all(0),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          itemBuilder: (BuildContext context, int index) {
            return _editExceptionDataDisplay(context, index);
          },
          separatorBuilder: (BuildContext context, int index) {
            return SizedBox(
              height: 0,
            );
          },
        )),
    );
  }

  bool _restNum(){
    if(StringUtils.isEmpty(punchuser?.dutytime)&&StringUtils.isEmpty(punchuser?.offdutytime)){
      return false;
    }else if(punchuser?.duration==null&&punchuser?.duration==""){
      return false;
    }else{
      return true;
    }
  }

  int _time(DayUserPunchListBean itemBean,index){
    DateTime dayUserTime = DateTime.now();
    // dynamic dutytime;//上班时间规则
    // int onFlextime;//上班弹性时间
    // dynamic offdutytime;//下班时间
    // int offFlextime;//下班弹性时间
    // int duration;//时长要求
    //如果有时长，那么根据时长判断。其次根据时间判断
    if(StringUtils.isNotEmpty(punchuser?.dutytime)&&StringUtils.isNotEmpty(punchuser?.offdutytime)){
      String punchTimeStr = "${dayUserTime?.toString()?.substring(0,10)} ${getFormatTime(itemBean?.punchTime)}";
      if(index==0){//第一次打卡判断是否迟到
        String punchuserDayTimeStr = "${dayUserTime?.toString()?.substring(0,10)} ${punchuser?.dutytime}";
        //getFormatTime(itemBean?.punchTime)
          if(VgDateTimeUtils.getStringToIntMillisecond(punchTimeStr) > VgDateTimeUtils.getStringToIntMillisecond(punchuserDayTimeStr)){
                return 1;
          }else{

            return 0;
          }
      }
      if((index+1) == dayUserPunchList?.length){//最后一次打卡是否早退
        String punchuserDayTimeStr = "${dayUserTime?.toString()?.substring(0,10)} ${punchuser?.offdutytime}";
        if(VgDateTimeUtils.getStringToIntMillisecond(punchTimeStr) < VgDateTimeUtils.getStringToIntMillisecond(punchuserDayTimeStr)){
                return 2;
        }else{
          return 0;
        }
      }
    }else if(punchuser?.duration==null){
      return 0;
    }else{
      return 0;
    }

  }
  ///时间秒转字符串
   String getFormatTime(int timeSecond) {
    if (timeSecond == null) {
      return null;
    }
    return DateUtil.formatDateMs(timeSecond * 1000, format: "HH:mm");
  }
  //新样式
  Widget _editExceptionDataDisplay(BuildContext context, int index) {
    final DayUserPunchListBean itemBean = dayUserPunchList?.elementAt(index);
    String temperature = "0";
    if(_temperature(itemBean)){
        temperature = itemBean?.temperature;
    }
    Color textColor = ThemeRepository.getInstance().getTextMainColor_D0E0F7();
    String text = VgToolUtils.getHourAndMinuteStr(itemBean?.punchTime) ?? "";
    if(_time(itemBean,index)==1 && !_rest()){//&& punchstatus=="99"
      textColor = ThemeRepository.getInstance().getMinorYellowColor_FFB714();
      text = text+"（迟到）";
    }
    if(_time(itemBean,index)==2 && !_rest()){//&& punchstatus=="99"
      textColor = ThemeRepository.getInstance().getMinorYellowColor_FFB714();
      text = text+"（早退）";
    }
    return Column(
      children: [
        //列表数据
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            //查看大头像
            // VgPhotoPreview.single(
            //     AppMain.context,
            //     showOriginEmptyStr(itemBean?.pictureUrl) ?? "");
            //错误后更换头像
            if(itemBean?.pictureUrl=="" || itemBean?.pictureUrl==null){
              return;
            }
            AttendPictureCorrectionWidget.navigatorPush(context,itemBean,faceuserBean,Cpid);
          },
          child: Container(
            height: itemBean?.backup!=null && itemBean?.backup!="" && itemBeanshowBackup == itemBean ? 104 :82,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.only(left: 15),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: <Widget>[
                          Text(
                            "${text} ",
                            style: TextStyle(fontSize: 15, color: textColor),
                          ),
                        ],
                      ),
                      Row(
                        children: <Widget>[
                          Container(
                            child: backupOrPositionText(itemBean),
                          ),
                        ],
                      ),
                      if(_temperature(itemBean))
                      Row(
                        children: <Widget>[
                          Container(
                            child: Text(_temperature(itemBean) ? "体温${_temperatureStr(itemBean) ?? ""}℃" :"",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: ((double?.parse(temperature)??0))>37.2 ? ThemeRepository.getInstance().getMinorRedColor_F95355() :Color(0xFF808388),
                                  height: 1.5),
                            ),
                          ),

                        ],
                      ),
                      if(itemBean?.backup!=null && itemBean?.backup!="" && itemBeanshowBackup == itemBean)
                        Container(
                          alignment: Alignment.topLeft,
                          height: 38,
                          width: VgToolUtils.getScreenWidth()*3/5,
                          // padding: const EdgeInsets.only(right: 10,left: 15),
                          child: Text(
                            "${itemBean?.backup ?? ""}  ",
                            style: TextStyle(fontSize: 12, color: Color(0xFF808388)),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        )
                    ],
                  ),
                ),
                Spacer(),
                ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Container(
                    height: 66,
                    // width: 120,
                    child: VgCacheNetWorkImage(
                      itemBean?.pictureUrl??"",
                      fit: BoxFit.cover,
                      imageQualityType: ImageQualityType.middleDown,
                        emptyWidget:_toDefaultHeadWidget(),
                        errorWidget:_toDefaultHeadWidget()
                      // defaultErrorType: ImageErrorType.head,
                      // defaultPlaceType: ImagePlaceType.head,
                    ),
                  ),
                ),
                SizedBox(width: 15,)
              ],
            ),
          ),
        ),
    if((index+1)==dayUserPunchList?.length)
     punchuser?.backup!=""&&punchuser?.backuptime!=null ? _reamrkText() : _addRemarksBar(),//备注框
      ],
    );
  }

  Widget _toDefaultHeadWidget(){
    return Container(
        width: 88,
        child: Image.asset("images/default_head_ico.png",fit: BoxFit.fitWidth,));
  }

  bool _temperature(DayUserPunchListBean itemBean){
    if(itemBean?.temperature!=null&& itemBean?.temperature!="" && itemBean?.temperature!="0.0"){
      return true;
    }else{
      return false;
    }
  }

  String _temperatureStr(DayUserPunchListBean itemBean){
    if((itemBean?.temperature?.length??0) > 4){
      return itemBean?.temperature?.substring(0,4);
    }else{
      return itemBean?.temperature;
    }
  }


  Widget _toHorizontalBar() {
      return Container(
        alignment: Alignment.bottomCenter,
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            SharePreferenceUtil.getInt(faceuserBean?.fuid).then((value){
              if(value==1){
                return;
              }else{
                //第一次如果为null，存入缓存1次
                SharePreferenceUtil.putInt(faceuserBean?.fuid??"", 1);
                AttendRecordCalendarPage.navigatorPush(context, widget.fuid);
              }

            });
          },
          child: Container(
            height: 50 + ScreenUtils.getBottomBarH(context),
            padding: EdgeInsets.only(bottom: ScreenUtils.getBottomBarH(context)),
            color: Color(0xFF3A3F50),
            // margin: const EdgeInsets.symmetric(horizontal: 15),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                SizedBox(
                  width: 15,
                ),
                Text("本月出勤",
                    style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 15)),
                Spacer(),
                Text("共${listBean?.data?.monthPunchCnt??0}天",
                    style: TextStyle(color: Color(0xFF1890FF), fontSize: 15)),
                SizedBox(
                  width: 10,
                ),
                Image.asset(
                  "images/index_arrow_ico.png",
                  width: 6,
                  height: 11,
                ),
                SizedBox(
                  width: 15,
                ),
              ],
            ),
          ),
        ),
      );
  }
  Widget backupOrPositionText(DayUserPunchListBean itemBean){
    if(itemBean?.createdate!=null && itemBean?.createdate!=""){
      String name = itemBean?.name ?? "";
      if("01" == (itemBean?.type??"")){
        //手动打卡
        name = name + "手动打卡";
      }
      return Row(
        children: [
          Container(
            // width: 150,
            child: Text(
              "${name}  ${VgToolUtils?.getHourAndMinuteByFormatStr(itemBean?.createdate)}",
              style: TextStyle(fontSize: 12, color: Color(0xFF808388)),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          if(itemBean?.backup!=null && itemBean?.backup!="")
          GestureDetector(
            onTap: (){
              if(itemBeanshowBackup == null){
                itemBeanshowBackup = itemBean;
              }else{
                itemBeanshowBackup = null;
              }

              setState(() { });
            },
            child: Text(
              "  查看备注",
              style: TextStyle(fontSize: 12, color: ThemeRepository.getInstance().getPrimaryColor_1890FF()),
            ),
          ),
        ],
      );
    }else{
      return Container(
        width: VgToolUtils.getScreenWidth()*3/5,
        child: Text(
          "${itemBean?.position ?? ""}",
          style: TextStyle(fontSize: 12, color: Color(0xFF808388)),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      );
    }
  }

  Widget _changeableDataCorrectionBar() {
    Color _correctionBarColor = Colors.transparent;
    // rest  00  休息日  01工作日
    // normal  00 正常  01异常
    // absence  00 缺勤  01出勤
    // overtime  00 加班 01不加班
    /// 上班状态 00出勤01缺勤 02纠正 03加班 04非加班 05请假 06外出 07确定加班 99异常'
    bool _exhibition = false;
    if(punchstatus == "02"){//纠正状态
      if (punchstatusCorrect == "00" || punchstatusCorrect == "99") {
        correctionBarText = "异常";
        _correctionBarColor = Color(0xFFFFB714);
        _exhibition = true;
      }

      if (punchstatusCorrect == "01") {
        correctionBarText = "缺勤";
        _correctionBarColor = Color(0x33F95355);
        _exhibition = true;
      }
      if (punchstatusCorrect == "05") {
        correctionBarText = "请假";
        _correctionBarColor = Color(0x33F95355);
        _exhibition = true;
      }
      if (punchstatusCorrect == "03" || punchstatusCorrect == "07"|| punchstatusCorrect == "04") {
        correctionBarText = "加班";
        _correctionBarColor = Color(0x3300C6C4);
        _exhibition = true;
      }
    }else{
      if (punchstatus == "99" || punchstatusCorrect == "99") {
        correctionBarText = "异常";
        _correctionBarColor = Color(0xFFFFB714);
        _exhibition = true;
      }else if (punchstatus == "01") {
        correctionBarText = "缺勤";
        _correctionBarColor = Color(0x33F95355);
        _exhibition = true;
      }else if (punchstatus == "05") {
        correctionBarText = "请假";
        _correctionBarColor = Color(0x33F95355);
        _exhibition = true;
      }else if(punchstatus == "03"||punchstatus=="04" ||punchstatus=="07"){
          correctionBarText = "加班?";
          _correctionBarColor = Color(0x3300C6C4);
          _exhibition = false;
      }else if(punchstatus=="00"){
        correctionBarText = "正常";
        _correctionBarColor = ThemeRepository.getInstance().getTextMainColor_D0E0F7();
        _exhibition = false;
      }
    }
    //如果是加班



    // if(dayUserPunchList?.length == 0){
    //   correctionBarText = "正常";
    //   _correctionBarColor = Colors.white;
    //   _exhibition = false;
    // }
    if(operatorInfoBean == null)type = "01";
    return Column(
      children: [
          _otherStaticBar(_correctionBarColor,_exhibition),
        if(dayUserPunchList?.length!=0 &&_restNum())
        dayUserPunchList?.length == 1 ?_attendNum() :_durationAttend()
      ],
    );
  }

  Widget _otherStaticBar(Color _correctionBarColor,bool _exhibition){
    //加班展示
    if(punchstatus=="03"||punchstatus=="04" ||punchstatus=="07"){
      // 上班状态 00出勤01缺勤 02纠正 03加班 04非加班 05请假 06外出 07确定加班 99异常'
      if(punchstatus=="04"){//否定加班
        correctionBarText = "非加班";
      }else if(punchstatus=="07"){//加班
        correctionBarText = "加班";
      }
      return Container(
        color: punchstatus=="04" ? ThemeRepository.getInstance().getCardBgColor_21263C() : _correctionBarColor?.withOpacity(0.2),
        child: Row(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.only(
                  left: 15,
                ),
                height: 45,
                child: Text(
                  correctionBarText,
                  style: TextStyle(
                      fontSize: 15,
                      color:punchstatus=="04" ?ThemeRepository.getInstance().getTextMainColor_D0E0F7() : _correctionBarColor?.withOpacity(1)),
                )),
            Spacer(),
            // _workOvertimeButton()
            punchstatus!="03" ? _textNotOvertime() :_workOvertimeButton()
          ],
        ),
      );
    }
    //请假和外出/加班不需要展示
    else if(!(punchstatus=="06" || punchstatus=="03" ||punchstatus=="04" ||punchstatus=="07" )){
      return Container(
        color: _correctionBarColor?.withOpacity(0.2),
        child: Row(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            type == "00"
                ? _stringJiuZhengText(_correctionBarColor)
                : _StringHuanYuanText(_correctionBarColor),
            Spacer(),
            if (_exhibition) _correctionButton(),
          ],
        ),
      );
    }else{
      return Container();
    }
  }

  Widget _workOvertimeButton() {
    return Container(
      padding: const EdgeInsets.only(right: 15),
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              viewModel.setDayPunchOvertime(Cpid, "01", BaseCallback(onSuccess: (val) {
                widget?.onChanged?.call();
                refreshData();
              }, onError: (msg) {
                VgToastUtils.toast(context, msg);
              }));
              setState(() { });
            },
            child: Container(
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.white, width: 1),
                  borderRadius: BorderRadius.circular(14)),
              height: 24,
              width: 56,
              alignment: Alignment.center,
              child: Text(
                "否",
                style: TextStyle(fontSize: 12, color: Colors.white, height: 1.3),
              ),
            ),
          ),
          SizedBox(width: 8,),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              viewModel.setDayPunchOvertime(Cpid, "00", BaseCallback(onSuccess: (val) {
                widget?.onChanged?.call();
                refreshData();
              }, onError: (msg) {
                VgToastUtils.toast(context, msg);
              }));
              setState(() { });
            },
            child: Container(
              // color: Color(0x3300C6C4)?.withOpacity(1),
              decoration: BoxDecoration(
                  color: Color(0x3300C6C4)?.withOpacity(1),
                  // border: Border.all(color: Color(0x3300C6C4)?.withOpacity(1)),
                  borderRadius: BorderRadius.circular(14)),
              height: 24,
              width: 56,
              alignment: Alignment.center,
              child: Text(
                "是",
                style: TextStyle(fontSize: 12, color: Colors.white, height: 1.3),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _textNotOvertime(){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        setState(() { });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            Text(
              punchstatus=="07" ?"${UserRepository.getInstance().userData.comUser.name}确认加班" :"${UserRepository.getInstance().userData.comUser.name}否认加班",
              style: TextStyle(
                  fontSize: 12,
                  color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
            ),
            GestureDetector(
              onTap: (){
                if (correctionBarText == "加班") {
                  punchstatusCorrect = "03";
                  punchstatus = "03";
                }else if(correctionBarText == "加班?"){
                  punchstatusCorrect = "03";
                  punchstatus = "03";
                }
                type = "01";
                setModifyAttendanceData(BaseCallback(onSuccess: (val) {
                  widget?.onChanged?.call();
                  refreshData();
                }, onError: (msg) {
                  VgToastUtils.toast(context, msg);
                }));
                setState(() { });
              },
              child: Text(
                "点击还原",
                style: TextStyle(
                    fontSize: 12,
                    decoration: TextDecoration.underline,
                    color: ThemeRepository.getInstance().getPrimaryColor_1890FF()),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _durationAttend(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.only(left: 15,top: 12,bottom: 12),
      child:Row(
        children: [
          Text(
            _computingTime(),
            style: TextStyle(
                color:
                !(_computingTime()?.contains("总"))? ThemeRepository.getInstance().getTextMainColor_D0E0F7() :  ThemeRepository.getInstance().getMinorYellowColor_FFB714(),
                fontSize: 15),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              // _computingTime();
              setUserPunchRecordRecalculate(BaseCallback(onSuccess: (val) {
                // widget?.onChanged?.call();
                // refreshData();
              }, onError: (msg) {
                VgToastUtils.toast(context, msg);
              }));
              setState(() { });
            },
            child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Text(
                  "重新计算",
                  style: TextStyle(
                      color:
                      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                      fontSize: 12),
                )),
          ),
        ],
      ),
    );
  }

  Widget _attendNum(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.only(left: 15,top: 12,bottom: 12),
      child:Row(
        children: [
          Text("刷脸${dayUserPunchList?.length}次",style: TextStyle(color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),fontSize: 15),),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              setUserPunchRecordRecalculate(BaseCallback(onSuccess: (val) {
                // widget?.onChanged?.call();
                // refreshData();
              }, onError: (msg) {
                VgToastUtils.toast(context, msg);
              }));
              setState(() { });
            },
            child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Text(
                  "重新计算",
                  style: TextStyle(
                      color:
                      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                      fontSize: 12),
                )),
          ),
        ],
      ),
    );
  }

  bool _rest(){
    if(punchstatus=="03"||punchstatus=="04" ||punchstatus=="07"){return true;}else return false;
  }
    //规则时间区间
  String _computingTime(){
    DateTime dayUserTime = DateTime.now();
    if(StringUtils.isNotEmpty(punchuser?.dutytime)&&StringUtils.isNotEmpty(punchuser?.offdutytime)) {
      //上下班时间//转换为秒
      int dutytimeDayTimeStr = VgDateTimeUtils.getStringToIntMillisecond("${dayUserTime?.toString()?.substring(0, 10)} ${punchuser?.dutytime}") ?? 0;
      int offdutytimeDayTimeStr = VgDateTimeUtils.getStringToIntMillisecond("${dayUserTime?.toString()?.substring(0, 10)} ${punchuser?.offdutytime}") ?? 0;
      int ruleTime  = offdutytimeDayTimeStr  - dutytimeDayTimeStr;
      if(dayUserPunchList?.length > 1){
        //第一次打卡判断
        String punchTimeStr = "${dayUserTime?.toString()?.substring(0,10)} ${getFormatTime(dayUserPunchList?.elementAt(0)?.punchTime)}";
        String overTimeStr = "${dayUserTime?.toString()?.substring(0,10)} ${getFormatTime(dayUserPunchList?.elementAt(dayUserPunchList?.length-1)?.punchTime)}";
        int workingHours = VgDateTimeUtils.getStringToIntMillisecond(overTimeStr) - VgDateTimeUtils.getStringToIntMillisecond(punchTimeStr);
        if((workingHours - (punchuser?.duration??0)) <= 0 && punchuser?.duration!=null && punchuser?.duration!=0){
          // String recordInsufficientStr = "出勤总时长不够${VgToolUtils.getDifferenceTimeStr(dutytimeDayTimeStr,offdutytimeDayTimeStr)}";
          // if(punchuser?.duration!=null && punchuser?.duration!=0){//时长判断
          // var date = (punchuser?.duration??0)/3600;
          // recordInsufficientStr = "出勤总时长不够${getFormatTimeStr(punchuser?.duration)}";
          // }
          //计算规则时间差转字符串
          return "出勤总时长不够${getFormatTimeStr(punchuser?.duration)}";
        }else if((workingHours - ruleTime) >= 0){
          //最后一次打卡判断
          // if(VgDateTimeUtils.getStringToIntMillisecond(overTimeStr) > offdutytimeDayTimeStr){
            String recordStr = VgToolUtils.getDifferenceTimeStr(VgDateTimeUtils.getStringToIntMillisecond(punchTimeStr),VgDateTimeUtils.getStringToIntMillisecond(overTimeStr));
            if(workingHours>=ruleTime){//工作时长与规则相等
              return recordStr = "出勤${recordStr}";
            }
          // }
        }else{
          return "出勤${getFormatTimeStr(workingHours)}";
        }
      }
    }else{
      return "";
    }
  }

  ///时间秒转字符串
    String getFormatTimeStr(int sub) {
      if (sub == null) {
        return null;
      }
      if (sub == 0) {
        return "1分钟";
      }
      int hour = ((sub) / 3600).floor();
      int minute = ((sub - (hour * 3600 ))  / 60).floor();

      if ((hour == null || hour <= 0) && (minute == null || minute <= 0)) {
        return null;
      }
      if (hour == null || hour <= 0) {
        if (minute <= 1) {
          return "1分钟";
        }
        return "$minute分钟";
      }
      if (minute <= 0) {
        return "$hour小时";
      }
      return "$hour小时$minute分钟";
    }


  Widget _StringHuanYuanText(Color _correctionBarColor) {
    return Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.only(
          left: 15,
        ),
        height: 45,
        child: Text(
          correctionBarText ?? "正常",
          style: TextStyle(
              fontSize: 15,
              color: _correctionBarColor?.withOpacity(1)),
        ));
  }

  Widget _stringJiuZhengText(Color _correctionBarColor) {
    return Container(
      alignment: Alignment.center,
      padding: const EdgeInsets.only(
        left: 15,
      ),
      height: 45,
      child: Row(
        children: <Widget>[
          Text(
            correctionBarText ?? "正常",
            style: TextStyle(
                fontSize: 15,
                color: _correctionBarColor?.withOpacity(1)),
          ),
          SizedBox(
            width: 6,
          ),
          Image.asset(
            "images/right_arrow_ioc.png",
            width: 16,
          ),
          SizedBox(
            width: 6,
          ),
          Text(
            "正常",
            style: TextStyle(fontSize: 15, color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
          ),
        ],
      ),
    );
  }

  Widget _correctionButton() {
    return Container(
      padding: const EdgeInsets.only(right: 15),
      child: type == "00"//00纠正 01还原
          ? _withdrawChangeData()
          : GestureDetector(
              onTap: () {
                if (correctionBarText == "异常") {
                  punchstatusCorrect = "99";
                  punchstatus = "02";
                }
                if (correctionBarText == "缺勤") {
                  punchstatusCorrect = "01";
                  punchstatus = "02";
                }
                if (correctionBarText == "请假") {
                  punchstatusCorrect = "05";
                  punchstatus = "02";
                }
                type = "00";
                setModifyAttendanceData(BaseCallback(onSuccess: (val) {
                  widget?.onChanged?.call();
                  refreshData();
                }, onError: (msg) {
                  VgToastUtils.toast(context, msg);
                }));
                setState(() {});
              },
              child: Container(
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.white, width: 1),
                    borderRadius: BorderRadius.circular(14)),
                height: 24,
                width: 56,
                alignment: Alignment.center,
                child: Text(
                  "纠正",
                  style:
                      TextStyle(fontSize: 12, color: Colors.white, height: 1.3),
                ),
              ),
            ),
    );
  }

  Widget _withdrawChangeData() {
    return Container(
      child: GestureDetector(
        onTap: () {
          if (correctionBarText == "异常") {
            punchstatusCorrect = "99";
            punchstatus = "99";
          }
          if (correctionBarText == "缺勤") {
            punchstatusCorrect = "01";
            punchstatus = "01";
          }
          if (correctionBarText == "请假") {
            punchstatusCorrect = "05";
            punchstatus = "05";
          }
          type = "01";
          setModifyAttendanceData(BaseCallback(onSuccess: (val) {
            widget?.onChanged?.call();
            refreshData();
          }, onError: (msg) {
            VgToastUtils.toast(context, msg);
          }));
          setState(() {});
        },
        child: Text.rich(
          TextSpan(children: [
            TextSpan(
              text:
                  "${operatorInfoBean?.name ?? UserRepository.getInstance().userData?.comUser?.name}纠正，",
              style: TextStyle(
                  fontSize: 12, color: Color(0xFFD0E0F7), height: 1.3),
            ),
            TextSpan(
              text: "点击还原",
              style: TextStyle(
                  fontSize: 12,
                  color: Colors.blue,
                  height: 1.3,
                  decoration: TextDecoration.underline),
            ),
          ]),
        ),
      ),
    );
  }

  Widget _defaultEmptyCustomWidget() {
    return Expanded(
      child: Offstage(
        offstage: showBackup ?? true,
        child: Container(
          padding: const EdgeInsets.only(top: 155),
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Image.asset("images/empty_icon.png",width: 115,gaplessPlayback: true,),
                Text(
                  "暂无刷脸记录",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: VgColors.INPUT_BG_COLOR,
                    fontSize: 13,
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
